<template>
  <div class="xiaobu-container" v-closeSelect="'window'">
    <div class="left-box flex-shrink" :style="{ width: width + 'px' }">
      <div class="tree-block pb-lg">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText">
        </el-input>
        <el-tree
          node-key="menuId"
          :default-expanded-keys="['ROOT_VALUE']"
          highlight-current
          class="filter-tree"
          :props="defaultProps"
          :data="menuData"
          :filter-node-method="filterNode"
          @node-click="handleSelect"
          ref="tree"
        >
        </el-tree>
      </div>
      <xiaobu-drag class="myxhandle" @widthChange="widthChange" />
    </div>
    <div
      class="right-box flex-grow"
      :style="{ width: `calc(100% - ${width}px)` }"
    >
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        class="search-form clearfix"
      >
        <el-form-item
          class="search-field fl five-per-row"
          label="菜单名称"
          prop="menuName"
        >
          <el-input
            v-model.trim="queryParams.menuName"
            placeholder="请输入菜单名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item
          class="search-field fl five-per-row"
          label="菜单类型"
          prop="menuType"
        >
          <el-select-dict
            dictType="MENU_TYPE"
            clearable
            placeholder="请选择菜单类型"
            v-model="queryParams.menuType"
            @dictChange="handleQuery"
          ></el-select-dict>
        </el-form-item>
        <el-form-item
          class="search-field fl five-per-row"
          label="状态"
          prop="status"
        >
          <el-select-dict
            dictType="STATUS"
            clearable
            placeholder="请选择状态"
            v-model="queryParams.status"
            @dictChange="handleQuery"
          ></el-select-dict>
        </el-form-item>
        <el-form-item
          class="search-field fl five-per-row"
          label="创建时间"
          prop="beginTime"
        >
          <el-date-picker
            v-model="dateRange"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            @change="handleQuery"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item class="fr">
          <el-button plain @click="resetQuery">重 置</el-button>
          <el-button type="primary" @click="handleQuery">查 询</el-button>
        </el-form-item>
      </el-form>
      <div class="table-wrap">
        <div class="table-control-box">
          <el-button
            v-hasPermi="['system:menu:create']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
          <el-button
            v-hasPermi="['system:menu:update']"
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            >编辑</el-button
          >
          <el-button
            v-hasPermi="['system:menu:delete']"
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleBatchDelete"
            >删除</el-button
          >
        </div>
        <div class="table-box">
          <el-table
            ref="menuTable"
            :class="{'empty': list.length === 0}" 
            empty-text=" "
            v-loading="loading"
            :data="list"
            row-key="menuId"
            @selection-change="handleSelectionChange"
            @row-click="clickRow"
          >
            <el-table-column
              :selectable="checkSelectable"
              :reserve-selection="true"
              type="selection"
              width="55"
              align="center"
            />
            <el-table-column
              label="菜单名称"
              prop="menuName"
              align="center"
              min-width="168px"
            />
            <el-table-column-dict
              label="菜单类型"
              prop="menuType"
              dictType="MENU_TYPE"
              align="center"
            />
            <el-table-column-dict
              dictType="STATUS"
              dictTypeNode="tag"
              label="状态"
              align="center"
              prop="status"
              min-width="100px"
            ></el-table-column-dict>
            <el-table-column-dict
              dictType="YES_NO"
              label="是否系统预设"
              align="center"
              width="128px"
              prop="isSystem"
            ></el-table-column-dict>
            <el-table-column-dict
              dateFormat="datetime"
              label="创建时间"
              align="center"
              width="168px"
              prop="createTime"
            ></el-table-column-dict>
            <el-table-column-dict
              defaultVal="--"
              label="最后更新时间"
              align="center"
              width="168px"
              prop="updateTime"
            ></el-table-column-dict>
            <el-table-column
              v-if="
                hasPermi([
                  'system:menu:status',
                  'system:menu:read',
                  'system:menu:delete',
                ])
              "
              label="操作"
              align="center"
              width="260px"
              fixed="right"
              class-name="small-padding "
            >
              <template slot-scope="scope">
                <el-button
                  v-hasPermi="['system:menu:status']"
                  :disabled="scope.row.isSystem === '1'"
                  size="mini"
                  :type="scope.row.status === '1' ? 'warning' : 'success'"
                  @click.native.stop="handleStatusChange(scope.row)"
                  >{{ scope.row.status === "1" ? "停用" : "启用" }}</el-button
                >
                <el-button
                  v-hasPermi="['system:menu:read']"
                  size="mini"
                  type="primary"
                  icon="el-icon-view"
                  @click.native.stop="handleUpdate(scope.row)"
                  >查看</el-button
                >
                <el-button
                  v-hasPermi="['system:menu:delete']"
                  :disabled="scope.row.isSystem === '1'"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click.native.stop="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </div>

    <!-- 添加或编辑对话框 -->
    <menu-dialog
      ref="menuDialog"
      :activeMenuPathList="activeMenuPathList"
      :menuData="menuData"
      :props="props"
      :parentMenuType="parentMenuType"
      :title="baseForm.menuId ? (isUpdate ? '编辑菜单' : '查看菜单') : '新增菜单'"
      :visible.sync="open"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :isUpdate="isUpdate"
      :baseForm="baseForm"
      @close="open = false"
      @successs="handleMenuChange"
      width="1024px"></menu-dialog>
  </div>
</template>

<script>
import { menuApi } from "@/api"
import MenuDialog from "./components/menu-dialog.vue"
export default {
  name: "systemMenuManage",
  components: {
    MenuDialog
  },
  data() {
    return {
      parentMenuType: "2", // 父级菜单类型
      width: 200,
      menuData: [], // 菜单树 数据
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      filterText: "",
      isUpdate: false, // 是否是编辑
      //搜索条件参数
      queryParams: {
        parentMenuId: "", // 父级菜单id
        menuName: "", // 名称
        menuType: "", // 
        status: "", //
        beginTime: "",
        endTime: "",
        pageNum: 1,
        pageSize: 10
      },
      dateRange: [],
      list: [],
      selection: [], //选中的项
      loading: false,
      total: 0,
      roleList: [],

      // 非单个禁用
      single: true,
      // 非多个禁用(0个禁用)
      multiple: true,

      open: false,
      // 表单参数
      baseForm: {
        parentMenuId: "", // 父级菜单
        menuType: "1", // 菜单类型
        pathType: "1", // path类型
        menuName: "", // 角色名
        name: "", // 页面权限标识
        path: "", // 菜单访问路径
        activeMenuPath: "", // 激活菜单路径
        order: 1, // 排序
        permissionIdentification: "", // 接口权限标识
        recycleBinIdentification: "", // 回收站数据表权限标识
        affix: "0", // 是否固定在标签栏
        showFooter: "1", // 是否展示底部信息
        breadcrumb: "1", // 是否展示在面包屑
        alwaysShow: "1", // 是否展示在侧边菜单
        icon: "", // 图标
        hidden: "0", // 是否隐藏 1 是 0 否
        cache: "0", // 是否缓存 1 是 0 否
        remark: "" // 备注
      },
      dialogForm: {}, // 弹框表单
      // 表单校验
      rules: {
        
      },
      props: {
        value: "menuId",
        label: "menuName",
        checkStrictly: true,
        emitPath: false
      },
      queryOptions: [],
      options: [], // 菜单值父元素id
      activeMenuPathList: [] // 可选的激活的菜单列表
    }
  },
  watch: {
    open(val) {
      if (!val) {
        this.isUpdate = false
        this.parentMenuType = ""
        this.baseForm = {
          parentMenuId: "", // 父级菜单
          menuType: "", // 菜单类型
          pathType: "1", // path类型
          menuName: "", // 角色名
          name: "", // 页面权限标识
          path: "", // 菜单访问路径
          activeMenuPath: "", // 激活菜单路径
          order: 1, // 排序
          permissionIdentification: "", // 接口权限标识
          recycleBinIdentification: "", // 回收站数据表权限标识
          affix: "0", // 是否固定在标签栏
          showFooter: "1", // 是否展示底部信息
          breadcrumb: "1", // 是否展示在面包屑
          alwaysShow: "1", // 是否展示在侧边菜单
          icon: "", // 图标
          hidden: "0", // 是否隐藏 1 是 0 否
          cache: "0", // 是否缓存 1 是 0 否
          remark: "" // 备注
        }
        this.$refs.menuDialog&&this.$refs.menuDialog.resetForm()
      }
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },

  async created() {
    await this.init()
  },
  methods: {
    // 初始化
    init() {
      const getArr = [
        this.handleQuery(),
        this.getParentIdList(),
        this.getActiveMenuPathList()
      ]
      return Promise.all(getArr)
    },
    // 菜单编辑或者新增成功事件
    async handleMenuChange() {
      this.$store.dispatch("user/getUserInfo")
      await this.init()
    },

    // 获取所有active可选菜单
    getActiveMenuPathList() {
      return menuApi.getActiveMenuPathList().then((data) => {
        this.activeMenuPathList = data
      })
    },

    /**
     * @description: 监听拉伸事件
     */
    widthChange(movement) {
      this.width -= movement
      if (this.width < 150) {
        this.width = 150
      }
      if (this.width > 700) {
        this.width = 700
      }
    },
    // 过滤父级菜单选项
    filterNode(value, data) {
      if (!value) {
        return true
      }
      return data.menuName.indexOf(value) !== -1
    },
    // 选中后数据
    handleSelect(data) {
      if (data.menuId === this.queryParams.parentMenuId) {
        return
      }
      this.queryParams.pageNum = 1
      if (data) {
        this.queryParams.parentMenuId = data.menuId
        this.parentMenuType = data.menuType
      } else {
        this.queryParams.parentMenuId = ""
        this.parentMenuType = ""
      }
      // 切换父级菜单时 清空已选项
      this.$refs.menuTable&&this.$refs.menuTable.clearSelection()
      this.getList()
    },
    // 获取菜单列表
    getParentIdList() {
      return menuApi.getMenuTree().then((data) => {
        if (data.length === 0) {
          this.menuData = [
            {
              menuName: "根菜单",
              menuId: "ROOT_VALUE",
              menuType: "2" // 目录类型菜单
            }
          ]
          return
        }
        this.menuData = [
          {
            menuName: "根菜单",
            menuId: "ROOT_VALUE",
            menuType: "2", // 目录类型菜单
            children: data
          }
        ]
      })
    },
    // 系统内设用户 禁止操作
    checkSelectable(row, index) {
      if (row.isSystem === "1") {
        return false
      } else {
        return true
      }
    },
    //点击行
    clickRow(row) {
      //系统预设用户 不做处理
      if (row.isSystem === "1") {
        return
      }
      this.$refs.menuTable&&this.$refs.menuTable.toggleRowSelection(row)
    },
    //批量删除用户
    handleBatchDelete() {
      let str = ""
      const ids = []
      for (let i = 0; i < this.selection.length; i++) {
        const item = this.selection[i]
        ids.push(item.menuId)
        str += item.menuName
        if (i !== this.selection.length - 1) {
          str += ", "
        }
      }

      this.$modal
        .confirm('是否确认删除菜单项为"【' + str + '】"的数据项？')
        .then(function() {
          return menuApi.batchDeleteItems({ ids })
        })
        .then(() => {
          this.init()
          this.$store.dispatch("user/getUserInfo")
          this.$modal.msgSuccess("批量删除菜单成功")
        })
        .catch(() => {})
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 清空已选项
      this.$refs.menuTable&&this.$refs.menuTable.clearSelection()
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.$refs.tree.setCurrentKey(null)
      this.queryParams.parentMenuId = ""
      this.baseForm.parentMenuId = ""
      this.handleQuery()
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true
      return menuApi
        .getList(this.addDateRange(this.queryParams, this.dateRange))
        .then((response) => {
          this.list = response.rows
          this.total = response.total
          this.loading = false
        })
        .catch((err) => {
          if (err?.name === "CanceledError") {
            return
          }
          this.loading = false
        })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.queryParams.parentMenuId === "") {
        this.$modal.msgWarning("请选择节点后再操作！")
        return
      }
      const treeTarget = this.$refs.tree.getCurrentNode()
      const params = {
        order: this.total + 1
      }
      if (treeTarget) {
        // 目录类型默认值为 菜单  菜单类型默认值为按钮
        params.menuType = treeTarget.menuType === "2" ? "1" : "3"
        params.parentMenuId = treeTarget.menuId
      } else {
        params.menuType = ""
        params.parentMenuId = ""
      }

      this.baseForm = Object.assign(this.baseForm, params)
      this.open = true
    },

    /** 编辑按钮操作 */
    handleUpdate(row) {
      if (!row.menuId) {
        this.isUpdate = true
      }
      const id = row.menuId || (this.selection[0] && this.selection[0].menuId)

      menuApi.getDetailById({ id }).then((data) => {
        this.baseForm = Object.assign(this.baseForm, data)
        this.open = true
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.menuId
      this.$modal
        .confirm('是否确认删除菜单为"' + row.menuName + '"的数据项？')
        .then(function() {
          return menuApi.deleteItem({ id })
        })
        .then(() => {
          this.init()
          // // 判断删除的项是否被勾选了
          // const flag = this.selection.find((item) => item.menuId === id)
          // flag && this.$refs.menuTable&&this.$refs.menuTable.toggleRowSelection(row, false)

          this.$store.dispatch("user/getUserInfo")
          this.$modal.msgSuccess("删除成功")
        })
    },
    // 状态改变事件
    handleStatusChange(row) {
      menuApi
        .changeStatus({
          menuId: row.menuId,
          status: row.status === "1" ? "0" : "1"
        })
        .then((data) => {
          this.getActiveMenuPathList()
          this.$store.dispatch("user/getUserInfo")
          this.$modal.msgSuccess("改变状态成功")
          this.getList()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.xiaobu-container {
  height: 100%;
  display: flex;
  .left-box {
    position: relative;
    margin-right: 12px;
    overflow-y: auto;
    overflow-x: hidden;
    min-height: calc(100vh - #{$LayoutHeaderHeight} - #{$LayoutTagsHeight} - 40px);
    padding: 12px;
    background: #ffffff;
    border-radius: 4px;
    .tree-block {
      height: 100%;
    }
  }
  .right-box {
  }
  .tips {
    font-size: 24px;
    margin-left: 12px;
    color: $mainColor;
  }
}
</style>
